package cn.yanxiaohui.service.web.pattern.linked.service;

import cn.yanxiaohui.data.entity.Linked;
import cn.yanxiaohui.data.mapper.LinkedMapper;
import cn.yanxiaohui.service.web.pattern.SpringUtils;
import cn.yanxiaohui.service.web.pattern.linked.NodeHandler;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class NodeServce {

    // 第一个节点
    private NodeHandler firstNodeHandler;

    @Autowired
    private LinkedMapper linkedMapper;

    @Autowired
    private SpringUtils springUtils;

    public NodeHandler getFirstNodeHandler(){
        if(firstNodeHandler != null){
            return firstNodeHandler;
        }
        // 1.查询所有节点
        List<Linked> linkedList = linkedMapper.getLinkedList();
        Map<String, Linked> map = new HashMap<String, Linked>(0);
        // 2.第一个节点
        Linked first = null;
        for (Linked node : linkedList) {
            map.put(node.getBeanId(), node);
            if(first == null && StringUtils.isBlank(node.getPreId())){
                first = node;
            }
        }

        firstNodeHandler = springUtils.getBean(first.getBeanId(), NodeHandler.class);
        String nextId = first.getNextId();
        NodeHandler temp = firstNodeHandler;
        while (nextId != null){
            Linked next = map.get(nextId);
            NodeHandler nextNddeHandler = springUtils.getBean(next.getBeanId(), NodeHandler.class);
            if(nextNddeHandler == null){
                break;
            }
            temp.setNextHandler(nextNddeHandler);
            temp = nextNddeHandler;
            nextId = next.getNextId();
        }


        return firstNodeHandler;
    }
}
